package com.haoxuer.discover.site.data.dao.impl;

import com.haoxuer.discover.data.core.CriteriaDaoImpl;
import com.haoxuer.discover.site.data.dao.WebTemplateDao;
import com.haoxuer.discover.site.data.entity.WebTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by imake on 2017年11月14日18:53:51.
 */
@Repository

public class WebTemplateDaoImpl extends CriteriaDaoImpl<WebTemplate, String> implements WebTemplateDao {
  
  @Override
  public WebTemplate findById(String id) {
    if (id == null) {
      return null;
    }
    return get(id);
  }
  
  @Override
  public WebTemplate save(WebTemplate bean) {
    
    getSession().save(bean);
    
    
    return bean;
  }
  
  @Override
  public WebTemplate deleteById(String id) {
    WebTemplate entity = super.get(id);
    if (entity != null) {
      getSession().delete(entity);
    }
    return entity;
  }
  
  @Override
  public String text(String templateid, Map<String, Object> keys) {
    String result = "";
    WebTemplate notice = findById(templateid);
    
    Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    config.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
    try {
      Template template = new Template(notice.getId(), notice.getNote(), config);
      Writer out = new StringWriter();
      template.process(keys, out);
      result = out.toString();
    } catch (TemplateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
  
  @Override
  protected Class<WebTemplate> getEntityClass() {
    return WebTemplate.class;
  }
  
  @Autowired
  public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
}